<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品唯一标识" prop="productMarking">
        <el-input
          v-model="queryParams.productMarking"
          placeholder="请输入产品唯一标识"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备类型" prop="deviceType">
        <el-select v-model="queryParams.deviceType" placeholder="请选择设备类型" clearable>
          <el-option
            v-for="dict in dict.type.device_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="产品状态" prop="productState">
        <el-select v-model="queryParams.productState" placeholder="请选择产品状态" clearable>
          <el-option
            v-for="dict in dict.type.device_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['dev:product:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['dev:product:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-row :gutter="20">
      <el-col style="margin-top:10px" :xs="24" :sm="12" :md="8" :lg="6" :xl="6" v-for="(item,index) in productList" :key="index">
        <el-card class="box-card productCon" shadow="hover" >
          <img style="width: 80px; height: 80px" v-if="item.photoUrl !== undefined" lazy :src='item.photoUrl' :preview-src-list="[item.photoUrl]" class="leftImage"/>
          <div class="productRight">
            <div class="productTop">
              <p>{{item.productName}}</p>
            </div>
            <el-row class="productBottom">
              <el-col :span="12">
                <p class="productText">产品唯一标识</p>
                <p>{{item.productMarking}}</p>
              </el-col>
              <el-col :span="12">
                <p class="productText">设备类型</p>
                <p> <dict-tag :options="dict.type.device_type" :value="item.deviceType"/> </p>
              </el-col>
            </el-row>
          </div>
        </el-card>
        <div class="buttonClass">
          <el-button type="primary" size="small" plain @click="handleUpdate(item)" v-hasPermi="['dev:product:edit']" icon="el-icon-edit" >编辑</el-button>
          <el-button v-if="item.productState == 1" type="primary" size="small" plain @click="enableDisable(item)" icon="el-icon-open">启用</el-button>
          <el-button v-if="item.productState == 0" type="danger" size="small" plain @click="enableDisable(item)" icon="el-icon-close">禁用</el-button>
          <el-button type="warning" size="small" plain  @click="handleDelete(item)" v-hasPermi="['dev:product:remove']" icon="el-icon-delete" >删除</el-button>
        </div>
      </el-col>
    </el-row>

    <pagination
      v-show="total>0"
      :total="total"
      :page-sizes="[12, 24, 50, 100]"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改产品管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="产品唯一标识" prop="productMarking">
          <el-input v-model="form.productMarking" placeholder="请输入产品唯一标识" />
        </el-form-item>
        <el-form-item label="所属品类" prop="productClassifiedId">
          <treeselect v-model="form.productClassifiedId" :options="productClassifiedIdOption" :normalizer="normalizer" placeholder="请选择父类型" />
        </el-form-item>
<!--        <el-form-item label="所属品类名称" prop="productClassifiedName">-->
<!--          <el-input v-model="form.productClassifiedName" placeholder="请输入所属品类名称" />-->
<!--        </el-form-item>-->
        <el-form-item label="设备类型" prop="deviceType">
          <el-select style="width:100%" v-model="form.deviceType" placeholder="请选择设备类型">
            <el-option
              v-for="dict in dict.type.device_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="所属项目" prop="projectId">-->
<!--          <el-input v-model="form.projectId" placeholder="请输入所属项目" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="项目名称" prop="projectName">-->
<!--          <el-input v-model="form.projectName" placeholder="请输入项目名称" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="所属部门" prop="deptId">-->
<!--          <el-input v-model="form.deptId" placeholder="请输入所属部门" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="部门名称" prop="deptName">-->
<!--          <el-input v-model="form.deptName" placeholder="请输入部门名称" />-->
<!--        </el-form-item>-->
        <el-form-item label="产品状态" prop="productState">
          <el-select style="width:100%" v-model="form.productState" placeholder="请选择产品状态">
            <el-option
              v-for="dict in dict.type.device_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="物模型定义" prop="metadata">-->
<!--          <el-input v-model="form.metadata" type="textarea" placeholder="请输入内容" />-->
<!--        </el-form-item>-->
        <el-form-item label="设备图标" prop="photoUrl">
          <image-upload v-model="form.photoUrl"/>
        </el-form-item>
<!--        <el-form-item label="连网方式" prop="networkWay">-->
<!--          <file-upload v-model="form.networkWay"/>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="消息协议ID" prop="messageProtocol">-->
<!--          <el-input v-model="form.messageProtocol" placeholder="请输入消息协议ID" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="消息协议名称" prop="protocolName">-->
<!--          <el-input v-model="form.protocolName" placeholder="请输入消息协议名称" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="传输协议" prop="transportProtocol">-->
<!--          <el-input v-model="form.transportProtocol" placeholder="请输入传输协议" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="数据存储策略相关配置" prop="storePolicyConfiguration">-->
<!--          <el-input v-model="form.storePolicyConfiguration" type="textarea" placeholder="请输入内容" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="设备接入方式名称" prop="accessName">-->
<!--          <el-input v-model="form.accessName" placeholder="请输入设备接入方式名称" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="设备接入方式" prop="accessProvider">-->
<!--          <el-input v-model="form.accessProvider" placeholder="请输入设备接入方式" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="数据存储策略" prop="storePolicy">-->
<!--          <el-input v-model="form.storePolicy" placeholder="请输入数据存储策略" />-->
<!--        </el-form-item>-->
        <el-form-item label="备注信息" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
<!--        <el-form-item label="删除标记" prop="delFlag">-->
<!--          <el-input v-model="form.delFlag" placeholder="请输入删除标记" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="预留字段1" prop="attr1">-->
<!--          <el-input v-model="form.attr1" placeholder="请输入预留字段1" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="预留字段2" prop="attr2">-->
<!--          <el-input v-model="form.attr2" placeholder="请输入预留字段2" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="预留字段3" prop="attr3">-->
<!--          <el-input v-model="form.attr3" placeholder="请输入预留字段3" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="预留字段4" prop="attr4">-->
<!--          <el-input v-model="form.attr4" placeholder="请输入预留字段4" />-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProduct, getProduct, delProduct, addProduct, updateProduct } from "@/api/dev/product";
import { listClassified } from "@/api/dev/classified";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "Product",
  components: {
    Treeselect
  },
  dicts: ['device_status', 'device_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品管理表格数据
      productList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 12,
        productName: null,
        productMarking: null,
        productClassifiedId: null,
        productClassifiedName: null,
        deviceType: null,
        projectId: null,
        projectName: null,
        deptId: null,
        deptName: null,
        productState: null,
        metadata: null,
        photoUrl: null,
        networkWay: null,
        messageProtocol: null,
        protocolName: null,
        transportProtocol: null,
        storePolicyConfiguration: null,
        accessName: null,
        accessProvider: null,
        storePolicy: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null
      },
      // 表单参数
      form: {},
      // 所属品类
      productClassifiedIdOption:[],
      // 表单校验
      rules: {
        productName: [
          { required: true, message: "产品名称不能为空", trigger: "blur" }
        ],
        productMarking: [
          { required: true, message: "产品唯一标识不能为空", trigger: "blur" }
        ],
        deviceType: [
          { required: true, message: "设备类型不能为空", trigger: "blur" }
        ],
        productState: [
          { required: true, message: "产品状态不能为空", trigger: "blur" }
        ],
        // delFlag: [
        //   { required: true, message: "删除标记不能为空", trigger: "blur" }
        // ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询产品管理列表 */
    getList() {
      this.loading = true;
      listProduct(this.queryParams).then(response => {
        this.productList = response.rows;
        this.productList.forEach(item => {
          item.photoUrl=process.env.VUE_APP_BASE_API+item.photoUrl
        })
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        productName: null,
        productMarking: null,
        productClassifiedId: null,
        productClassifiedName: null,
        deviceType: null,
        projectId: null,
        projectName: null,
        deptId: null,
        deptName: null,
        productState: null,
        metadata: null,
        photoUrl: null,
        networkWay: null,
        messageProtocol: null,
        protocolName: null,
        transportProtocol: null,
        storePolicyConfiguration: null,
        accessName: null,
        accessProvider: null,
        storePolicy: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        delFlag: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加产品管理";
      /**查询所属品类*/
      this.getListClassified();
    },
    /** 查询所属品类 */
    getListClassified() {
      let params={
        enableFlag: 1 // 查询启用
      }
      listClassified(params).then(res => {
        this.productClassifiedIdOption = this.handleTree(res.data, "id", "parentId");
      });
    },
    /** 转换设备类型数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.classifiedName,
        children: node.children
      };
    },
    handleNodeClick (data) {
      // console.log(data)
      this.form = {
        productClassifiedId: data.id,
        classifiedName:data.classifiedName
      }
      // 使 input 失去焦点，并隐藏下拉框
      this.$refs.selectTree.blur()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      // const id = row.id || this.ids
      // getProduct(id).then(response => {
      //   this.form = response.data;
      //   this.open = true;
      //   this.title = "修改产品管理";
      // });
      this.$router.push({ path: '/dev/product/detailPage', query: { id: row.id} })

    },
    /**启用禁用**/
    enableDisable(row) {
      this.$confirm('是否修改该产品状态?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const id = row.id || this.ids
        getProduct(id).then(response => {
          let state = response.data.productState
          if(state == 0){
            response.data.productState = 1
          }else {
            response.data.productState = 0
          }
          updateProduct(response.data).then(res => {
            this.$modal.msgSuccess("产品状态修改成功");
            this.getList();
          });
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消修改'
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateProduct(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProduct(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除该产品？').then(function() {
        return delProduct(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('dev/product/export', {
        ...this.queryParams
      }, `product_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
  .productCon{
    cursor: pointer;
    margin-bottom: 10px;
  }
  /deep/ .productCon .el-card__body{
    display: flex !important;
    align-items: center !important;
  }
  .productRight{
    width: calc(100% - 95px);
    margin-left: 15px;
  }
  .productRight p{
    margin: 0;
  }
  .productTop{
    margin-bottom: 10px;
  }
  .productBottom p{
    font-size: 14px;
    padding-top: 5px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .productText{
    font-size: 12px;
    color: #000000b3;
  }
  .productCon .el-image{
    background: #fff;
    box-shadow:none;
  }
  /deep/ .productCon .el-image__preview{
    object-fit: unset !important;
    transition:none !important;
  }
  /deep/ .productCon .el-image .el-image__inner:hover{
    transform:none !important;
  }
  .buttonClass{
    display: flex;
  }
  .buttonClass .el-button{
    /*display: flex;*/
    /*flex-grow: 1;*/
    width: 100%;
    text-align: center;
  }
</style>
